//
//  HomeDetailsViewController.m
//  aMoment
//
//  Created by dllo on 15/10/13.
//  Copyright © 2015年 LuckyHan. All rights reserved.
//

#import "HomeDetailsViewController.h"
#import "AllHeaderFiles.h"

@interface HomeDetailsViewController ()<UIWebViewDelegate, UMSocialUIDelegate>
@property(nonatomic, retain)UIWebView *webView;
@property(nonatomic, assign)NSInteger flag;
@property(nonatomic, retain)NSDictionary *shareInfo;
@property(nonatomic, retain)Record *record;
@property(nonatomic, retain)MBProgressHUD *progressView;
@end

@implementation HomeDetailsViewController

- (void)dealloc
{
    [_webView release];
    [_shareInfo release];
    [_record release];
    [_progressView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIBarButtonItem *collectButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-starempty@2x"] style:UIBarButtonItemStylePlain target:self action:nil];
    UIBarButtonItem *shareButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-share@2x"] style:UIBarButtonItemStylePlain target:self action:nil];
    self.navigationItem.rightBarButtonItems = @[collectButton, shareButton];
    [self getData];
}

#pragma mark 收藏方法
- (void)collectAction
{
    [DatabaseManager createTable];
    if (!_flag) {
        [DatabaseManager insertRecord:_record];
        self.navigationItem.rightBarButtonItems.firstObject.image = [UIImage imageNamed:@"iconfont-starfull@2x"];
        _flag = 1;
    } else {
        [DatabaseManager deleteRecord:_contentId];
        self.navigationItem.rightBarButtonItems.firstObject.image = [UIImage imageNamed:@"iconfont-starempty@2x"];
        _flag = 0;
    }
}

#pragma mark 分享方法
- (void)shareAction
{
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"562490db67e58ef75f001384" shareText:[NSString stringWithFormat:@"%@\n%@", [_shareInfo objectForKey:@"text"], [_shareInfo objectForKey:@"url"]] shareImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[_shareInfo objectForKey:@"pic"]]]] shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina, nil] delegate:self];
}

#pragma mark 获取数据
- (void)getData
{
    self.shareInfo = [NSDictionary dictionary];
    [NetworkRequest getDataWithURLString:@"http://api2.pianke.me/article/info" BodyString:[NSString stringWithFormat:@"contentid=%@&client=2", _contentId] DataBlock:^(id data) {
        //移除加载中提示视图
        [_progressView removeFromSuperview];
        
        NSDictionary *dataDict = [(NSDictionary *)data objectForKey:@"data"];
        NSString *htmlString = [self deleteHyperlinkStringWithHtmlString:[dataDict objectForKey:@"html"]];
        [_webView loadHTMLString:htmlString baseURL:nil];
        
        self.shareInfo = [dataDict objectForKey:@"shareinfo"];
        //创建收藏对象
        _record = [[Record alloc] init];
        _record.contentId = _contentId;
        _record.itemName = @"Home";
        _record.title = [_shareInfo objectForKey:@"title"];
        
        //查询数据库
        [self searchDatabase:_record.title];
        
        [self.navigationItem.rightBarButtonItems.firstObject setAction:@selector(collectAction)];
        [self.navigationItem.rightBarButtonItems.lastObject setAction:@selector(shareAction)];
    }];
}

#pragma mark 删除html里的超链接
- (NSString *)deleteHyperlinkStringWithHtmlString:(NSString *)htmlString
{
    NSArray *htmlStringArray = [htmlString componentsSeparatedByString:@"<a "];
    htmlString = [NSString string];
    for (NSString *str in htmlStringArray) {
        htmlString = [htmlString stringByAppendingFormat:@"%@", [str componentsSeparatedByString:@"</a>"].lastObject];
    }
    return htmlString;
}

#pragma mark html加载完毕
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //------------------------------------------------------------
    //修改JS语言
    //定义JS字符串(JavaScript)
    NSString *script = [NSString stringWithFormat:@"var script = document.createElement('script');"
                        "script.type = 'text/javascript';"
                        "script.text = \"function ResizeImages() { "
                        "var myimg;"
                        "var maxwidth = %f;"//屏幕宽度
                        "for (i = 0; i < document.images.length; i++) {"
                        "myimg = document.images[i];"
                        "myimg.height = maxwidth / (myimg.width / myimg.height);"
                        "myimg.width = maxwidth;"
                        "}"
                        "}\";"
                        "document.getElementsByTagName('p')[0].appendChild(script);", SCREEN_WIDTH - 15 * FIT_WIDTH];
    //添加JS
    [webView stringByEvaluatingJavaScriptFromString:script];
    //添加调用JS执行的语句
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    //------------------------------------------------------------
}

- (void)loadView
{
    [super loadView];
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    _webView.backgroundColor = [UIColor whiteColor];
    _webView.delegate = self;
    [self.view addSubview:_webView];
    [_webView release];
    
    //创建加载中提示视图
    self.progressView = [LoadingProgress createViewWithSuperviewFrame:self.view.frame];
    [self.view addSubview:_progressView];
    [_progressView release];
}

#pragma mark 查询数据库
- (void)searchDatabase:(NSString *)title
{
    NSMutableArray *recordArray = [NSMutableArray arrayWithArray:[DatabaseManager selectRecords]];
    for (Record *record in recordArray) {
        if ([title isEqualToString:record.title]) {
            self.navigationItem.rightBarButtonItems.firstObject.image = [UIImage imageNamed:@"iconfont-starfull@2x"];
            _flag = 1;
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
